using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Activation;
using Castle.DynamicProxy;
using CosyTrade.Core;

namespace CosyTrade.Network.Proxy
{
    [Addin("RemotingProxyManager")]
    public class ProxyManager : AddinBase, IRemotingPortalFactory
    {
        private static readonly object LOCK_OBJECT = new object();
        private readonly Dictionary<Type, object> addinCache = new Dictionary<Type, object>();
        private IMethodInvoke methodInvoke; 

        protected override void OnInitialize()
        {
            methodInvoke =
                (IMethodInvoke) Activator.CreateInstance(typeof (MethodInvoke), null,
                                                         new object[] {new UrlAttribute(ConfigNode["server"].InnerText)});

        }

        public T RegisterProxy<T>(string addinName)
        {
            if (!addinCache.ContainsKey(typeof (T)))
                lock (LOCK_OBJECT)
                    if (!addinCache.ContainsKey(typeof (T)))
                    {
                        ProxyInterceptor interceptor = new ProxyInterceptor(methodInvoke, addinName);
                        ProxyGenerator generator = new ProxyGenerator();
                        ProxyGenerationOptions options = new ProxyGenerationOptions();
                        options.BaseTypeForInterfaceProxy = typeof(RemotingObject);

                        addinCache.Add(typeof (T), generator.CreateInterfaceProxyWithoutTarget(typeof (T), interceptor));
                    }
            return (T) addinCache[typeof (T)];
        }

        public T GetProxy<T>()
        {
            return (T) addinCache[typeof (T)];
        }
    }
}